/**
 * 浏览器升级引导.
 */
function upgrade() {

  //检查浏览器是否支持语音输入（目前仅 Chrome 支持）.
  if ('webkitSpeechRecognition' in window) {
    return false;
  }

  alert("请升级至 Chrome 浏览器最新版");
  console.log('浏览器不支持语音输入');

  return true;

}

/**
 * getElementById 缩写.
 * @param id {String}
 */
function getid(id) {
  return document.getElementById(id);
}

function capitalize(s) {
  return s.replace(/\S/, function(m) { return m.toUpperCase(); });
}

/**
 * 语音输入初始化程序.
 */
function init() {

  //升级引导程序.
  if ( upgrade() ) { return; }

  var startDOM = getid('start');
  var statusDOM = getid('status');
  var payDOM = getid('pay');

  //实例化语音接口.
  var recognition = new webkitSpeechRecognition();

  //最终的文本.
  var finalTranscript = '';
  //识别程序是否准备就绪.
  var recognizing = false;
  //忽略结束事件.
  var ignoreEnd = false;
  //开始识别的时间.
  var startTimestamp;

  recognition.continuous = true;
  recognition.interimResults = true;

  recognition.lang = 'en-US';

  recognition.onstart = function() {

    console.log('onstart');

    recognizing = true;
    startDOM.innerHTML = 'Stop';
    startDOM.className = 'actived';
    payDOM.innerHTML = '识别中...';
  };

  recognition.onerror = function(event) {

    console.log('onerror: ' + event.error);

    ignoreEnd = true;

    //错误处理.
    switch (event.error) {
      case 'no-speech':
        console.log('No speech was detected. You may need to adjust your <a href="//support.google.com/chrome/bin/answer.py?hl=en&amp;answer=1407892">microphone settings</a>.');
        ignoreEnd = true;
        break;
      case 'audio-capture':
        console.log('No microphone was found. Ensure that a microphone is installed and that <a href="//support.google.com/chrome/bin/answer.py?hl=en&amp;answer=1407892">microphone settings</a> are configured correctly.');
        ignoreEnd = true;
        break;
      case 'not-allowed':
        if (event.timeStamp - startTimestamp < 100) {
          console.log('Permission to use microphone is blocked. To change, go to');
          console.log('chrome://settings/contentExceptions#media-stream');
        } else {
          console.log('Permission to use microphone was denied.');
        }
        ignoreEnd = true;
        break;
      default:
        console.log('未知的错误');
        ignoreEnd = true;
    }

  };

  recognition.onend = function() {

    console.log('onend');
    recognizing = false;

    startDOM.innerHTML = 'Start';
    startDOM.className = '';
  };

  recognition.onresult = function(event) {

    console.log('onresult');
    //statusDOM.innerHTML = 'go on';

    if (typeof(event.results) == 'undefined') {
      console.log('浏览器太旧');
      recognition.stop();
      return;
    }

    //console.log(event);

    finalTranscript = event.results[0][0]['transcript'];
    //更新显示文本.
    payDOM.innerHTML = finalTranscript.replace(/\S/, function(m) {
      return m.toUpperCase();
    });

    //console.log(finalTranscript);

    //capitalize();

  };

  startDOM.addEventListener('click', function(event) {

    //如果正在识别，则停止.
    if (recognizing) {
      recognition.stop();
      return;
    }

    recognition.start();
    startTimestamp = event.timeStamp;

  }, false);


}

init();
